package com.wb.adutils

import android.app.Activity
import android.text.TextUtils
import com.bytedance.msdk.api.v2.GMAdConstant
import com.wb.adutils.ads.gmad.*
import com.wb.adutils.ads.pangle.*
import com.wb.adutils.callback.OnLoadAdListener
import com.wb.adutils.db.AdEntity
import com.wb.adutils.db.AdRoomUtils
import com.wb.adutils.tools.AdConstants
import com.wb.adutils.tools.LogC

object AdLoader {

    fun loadAd(activity: Activity, template: Int, callback: OnLoadAdListener, adUnit: String? = null, width: Int = 0, height: Int = 0, count: Int = 1, orientation: Int = GMAdConstant.VERTICAL): AdBaseLoader? {
        // 广告类型，主要是给详情广告使用，有插屏和激励  插屏0：激励：1
        val adEntity = if (template == AdConstants.AD_TEMPLATE_HOME_LIST) {
            if (!TextUtils.isEmpty(adUnit) && !AdUtils.isDebugModel()) {
                val temp = AdEntity()
                temp.adUnit = adUnit
                temp.adTemplate = AdConstants.AD_TEMPLATE_HOME_LIST
                temp
            } else {
                null
            }
        } else {
            AdRoomUtils.getInstance()?.adDao()?.queryAd(template)
        }
        if (TextUtils.isEmpty(adEntity?.adUnit)) {
            LogC.e("${AdUtils.getNameByTemplate(template)}广告没有配置...")
            callback.onAdComplete(true)
            return null
        }
        // 广告商
        val advertiser = adEntity?.advertiser?:0
        val adLoader = getAdLoader(template, advertiser, adEntity)
        adLoader?.loadAd(activity, template, width, height, count, orientation, object: OnLoadAdListener {

            private var isUpdateShowTime = false

            override fun onAdLoaded(ad: Any?) {
                callback.onAdLoaded(ad)
            }

            override fun onAdClicked() {
                super.onAdClicked()
                callback.onAdClicked()
            }

            override fun onAdDisplay(duration: Int?) {
                super.onAdDisplay(duration)
                callback.onAdDisplay(duration)

                updateAdShowTime()
            }

            override fun onAdLoadFail(errorCode: Int) {
                if (errorCode == AdConstants.AD_ERROR_CODE_MAX_REQUEST) {
                    callback.onAdLoadFail(errorCode)
                    return
                }
                // 加载广告失败，是否当做成 0：失败算成功，1：超时不算成功，2：失败时只有未填充算成功，3：失败就是失败，4：只有获得奖励才算成功
                if (adEntity?.failureHandling == 0) { // 失败算成功
                    excAdComplete()
                } else if (adEntity?.failureHandling == 1){ // 超时不算成功，其他都算成功
                    if (errorCode == AdConstants.AD_ERROR_CODE_TIMEOUT) {
                        callback.onAdLoadFail(errorCode)
                    } else {
                        excAdComplete()
                    }
                } else if (adEntity?.failureHandling == 2){ // 失败时只有未填充算成功
                    if (errorCode == 20001) { // sdk的请求成功未填充的返回值
                        excAdComplete()
                    } else {
                        callback.onAdLoadFail(errorCode)
                    }
                } else {
                    callback.onAdLoadFail(errorCode)
                }
            }

            override fun onAdComplete(isRewarded: Boolean) {
                if (adEntity?.failureHandling == 4) {
                    if (isRewarded) {
                        excAdComplete()
                    } else {
                        callback.onAdLoadFail(AdConstants.AD_ERROR_CODE_NO_REWARDED)
                    }
                } else {
                    excAdComplete()
                }
            }

            private fun excAdComplete(){
                callback.onAdComplete(true)
                if (adEntity?.adTemplate == AdConstants.AD_TEMPLATE_DOWNLOAD) {
                    adEntity.userDownloadCount += adEntity.downloadAddCount
                    adEntity.dayDownloadCount += 1
                }
                updateAdShowTime()
            }

            // 更新广告的展示时间
            private fun updateAdShowTime(){
                if (isUpdateShowTime) return
                isUpdateShowTime = true
                adLoader.updateAdShowTime()
            }

        })
        return adLoader
    }

    private fun getAdLoader(template: Int, advertiser: Int, adEntity: AdEntity?): AdBaseLoader? {
        val adLoader = when (template) {
            AdConstants.AD_TEMPLATE_EXIT -> {
                if (advertiser == 0) {
                    PangleBannerAdUtils(adEntity)
                } else {
                    GMBannerAdUtils(adEntity)
                }
            }
            AdConstants.AD_TEMPLATE_VIDEO -> {
                val type = adEntity?.adType ?: 1
                if (advertiser == 0) {
                    if (type == 0) PangleInterstitialAdUtils(adEntity) else PangleRewardAdUtils(adEntity)
                } else {
                    if (type == 0) GMInterstitialAdUtils(adEntity) else GMRewardAdUtils(adEntity)
                }

            }
            AdConstants.AD_TEMPLATE_VIDEO_PAUSE -> {
                if (advertiser == 0) {
                    PangleNativeAdUtils(adEntity)
                } else {
                    GMNativeAdUtils(adEntity)
                }
            }
            AdConstants.AD_TEMPLATE_VIDEO_BANNER -> {
                if (advertiser == 0) {
                    PangleNativeAdUtils(adEntity)
                } else {
                    GMNativeAdUtils(adEntity)
                }
            }
            AdConstants.AD_TEMPLATE_HOME_LIST -> {
                if (advertiser == 0) {
                    PangleNativeAdUtils(adEntity)
                } else {
                    GMNativeAdUtils(adEntity)
                }
            }
            AdConstants.AD_TEMPLATE_DOWNLOAD -> {
                if (advertiser == 0) {
                    PangleRewardAdUtils(adEntity)
                } else {
                    GMRewardAdUtils(adEntity)
                }
            }
            AdConstants.AD_TEMPLATE_SPLASH -> {
                if (advertiser == 0) {
                    PangleSplashUtils(adEntity)
                } else {
                    GMSplashUtils(adEntity)
                }
            }
            else -> null
        }
        return adLoader
    }


}